/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.goods.appweb;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.responseReturn.entity.ResultObject;
import com.jeesite.common.responseReturn.utils.CommonUtils;
import com.jeesite.common.responseReturn.web.Render;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.goods.entity.ZtCouponCode;
import com.jeesite.modules.goods.service.ZtCouponCodeService;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import com.jeesite.modules.xcxAdmin.service.ZtAdminService;

/**
 * 测试数据Controller
 * 
 * @author ThinkGem
 * @version 2018-04-22
 */
@Controller
@RequestMapping(value = "${frontPath}/ztCouponCode")
public class AppZtCouponCodeController extends BaseController {


	@Autowired
	ZtCouponCodeService ztCouponCodeService;
	@Autowired
	ZtAdminService ztAdminService;
	
	@Autowired
	private MyProps myProps;
	
	
	@RequestMapping(value = "coupon")
	@ResponseBody
	public void coupon( HttpServletRequest request,
			HttpServletResponse response,Model model) {
		
		String paramStr=CommonUtils.getParams(request);
		ResultObject res = new ResultObject();
		
		JSONObject jo=JSONObject.parseObject(paramStr);
		String adminid = jo.getString("adminid");
		String code = jo.getString("code");
		ZtCouponCode ztCouponCode=new ZtCouponCode();
		ztCouponCode.setCode(code);
		ztCouponCode=ztCouponCodeService.getByCode(ztCouponCode);
		if(ztCouponCode!=null && StringUtils.isNotBlank(ztCouponCode.getId())){
			
			if(!"0".equals(ztCouponCode.getState())){
				//无效
				res.setResult(300L);
				res.setMsg("券码已失效");
				Render.renderString(response, res);
				return;
			}
			if(!"0".equals(ztCouponCode.getIsuse())){
				//已使用
				res.setResult(400L);
				res.setMsg("券码已兑换");
				Render.renderString(response, res);
				
				return;
			}
			ZtAdmin ztAdmin =new ZtAdmin();
			ztAdmin.setId(adminid);
			ztAdmin=ztAdminService.get(ztAdmin);
			ztAdmin.setCashAmount(ztAdmin.getCashAmount()+ztCouponCode.getPrice());
			ztAdminService.save(ztAdmin);
			ztCouponCode.setIsuse("1");//已使用
			ztCouponCode.setCoupontime(new Date());
			ztCouponCodeService.save(ztCouponCode);
			res.setData(ztAdmin);
		}else{
			
				//无效
				res.setResult(304L);
				res.setMsg("无效券码");
				Render.renderString(response, res);
				return;
			
		}
		
		res.setResult(200L);
		
		Render.renderString(response, res);
	}
	
	
}